<?php

namespace Wonfu\Core\Database;

use Atlas\Mapper\MapperSelect;
use Atlas\Orm\Atlas;
use Symfony\Component\PropertyInfo\Extractor\PhpDocExtractor;
use Symfony\Component\PropertyInfo\Extractor\ReflectionExtractor;
use Symfony\Component\PropertyInfo\PropertyInfoExtractor;
use Symfony\Component\Serializer\Encoder\JsonEncoder;
use Symfony\Component\Serializer\Encoder\XmlEncoder;
use Symfony\Component\Serializer\Normalizer\ArrayDenormalizer;
use Symfony\Component\Serializer\Normalizer\JsonSerializableNormalizer;
use Symfony\Component\Serializer\Normalizer\ObjectNormalizer;
use Symfony\Component\Serializer\Serializer;

class BaseAtlas
{

    /**
     * @var string
     */
    protected $atlasMapper;

    /**
     * @var string
     */
    protected $entityClass;

    /**
     * @var Atlas
     */
    protected $atlas;

    /**
     * @return Atlas
     */
    public function getAtlas(): Atlas
    {
        return $this->atlas;
    }

    /**
     * @param Atlas $atlas
     */
    public function setAtlas(Atlas $atlas): void
    {
        $this->atlas = $atlas;
    }

    /**
     * @return MapperSelect
     */
    public function select():MapperSelect
    {
        return $this->atlas->select($this->atlasMapper);
    }


    public function insert($entity){
        $this->atlas->insert();
    }


    /**
     * @param $data
     * @return object|array
     */
    public function useObject($data)
    {
        if(is_array($data)){
            return BaseAtlas::ObjectMapper($data,$this->entityClass.'[]');
        }
        return BaseAtlas::ObjectMapper($data,$this->entityClass);

    }


    /**
     * @param mixed $data
     * @param string $mapper
     * @return mixed
     */
    public static function ObjectMapper($data, $mapper)
    {
        $encoders = [new XmlEncoder(), new JsonEncoder()];
        $extractor = new PropertyInfoExtractor([], [new PhpDocExtractor(), new ReflectionExtractor()]);
        $normalizers = [new ObjectNormalizer(null, null, null, $extractor),
            new ArrayDenormalizer(), new JsonSerializableNormalizer()];
        $serializer = new Serializer($normalizers, $encoders);
        return $serializer->deserialize($data, $mapper, 'json', [
            ObjectNormalizer::DISABLE_TYPE_ENFORCEMENT => true]);
    }


}